package com.ld.shieldsb.common.core.util;

public class IPUtil {

    /**
     * 
     * 判断是否在ip段内
     * 
     * @Title isInRange
     * @author 吕凯
     * @date 2019年5月16日 上午9:35:19
     * @param network
     * @param mask
     *            ip段，192.168.1.1-192.168.1.20或192.168.1.0/24 子网掩码的网络 void
     */
    public static boolean isInRange(String network, String mask) {
        if (mask.contains("-")) {//
            return ipExistsInRange(network, mask);
        } else if (!mask.contains("/")) {//
            return network.equals(mask);
        }
        String[] networkips = network.split("\\.");
        int ipAddr = (Integer.parseInt(networkips[0]) << 24) | (Integer.parseInt(networkips[1]) << 16)
                | (Integer.parseInt(networkips[2]) << 8) | Integer.parseInt(networkips[3]);
        int type = Integer.parseInt(mask.replaceAll(".*/", ""));
        int mask1 = 0xFFFFFFFF << (32 - type);
        String maskIp = mask.replaceAll("/.*", "");
        String[] maskIps = maskIp.split("\\.");
        int cidrIpAddr = (Integer.parseInt(maskIps[0]) << 24) | (Integer.parseInt(maskIps[1]) << 16) | (Integer.parseInt(maskIps[2]) << 8)
                | Integer.parseInt(maskIps[3]);

        return (ipAddr & mask1) == (cidrIpAddr & mask1);
    }

    /**
     * 
     * 验证IP是否属于某个IP段
     * 
     * @Title ipExistsInRange
     * @author 吕凯
     * @date 2019年5月16日 上午9:43:45
     * @param ip
     *            所验证的IP号码
     * @param ipSection
     *            IP段（以'-'分隔）
     * 
     * @return boolean
     */
    public static boolean ipExistsInRange(String ip, String ipSection) {
        ipSection = ipSection.trim();
        ip = ip.trim();
        int idx = ipSection.indexOf('-');
        String beginIP = ipSection.substring(0, idx);
        String endIP = ipSection.substring(idx + 1);
        return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);

    }

    public static long getIp2long(String ip) {
        ip = ip.trim();
        String[] ips = ip.split("\\.");
        long ip2long = 0L;
        for (int i = 0; i < 4; ++i) {
            ip2long = ip2long << 8 | Integer.parseInt(ips[i]);
        }
        return ip2long;

    }

}
